// pages/addOrder/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    myCat:[],
    addressList:[],
    addressIndex:0,
    remark: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var myCat = wx.getStorageSync('myCat')
    var total = 0;
    var orderDetailList = [];
    for(var i=0;i<myCat.length;i++){
      total = total + myCat[i].price*myCat[i].num
      var dict ={'productId':myCat[i].id,'num':myCat[i].num,'price':myCat[i].price,'pic':myCat[i].pic,'name':myCat[i].name}
      orderDetailList.push(dict)
    }
    that.setData({
      myCat:orderDetailList,
      total:total
    })

    var token = wx.getStorageSync('token');
    var user = wx.getStorageSync('user');
    var that = this;
    wx.request({
      url: 'http://127.0.0.1:8080/system/address/list?userId='+user.userId, // 获取地址列表接口
      method: 'get',
      header: {
        'content-type': 'application/json',  //这里注意POST请求content-type是小写，大写会报错
        'Authorization': token
      },
      success(res) {
        if (res.statusCode==200) {
          that.setData({
            addressList:res.data.rows
          })
        }
      }
    })
  },

  // 监听选择地址
  areaInput: function(e) {
    this.setData({
      addressIndex: e.detail.value
    })
  },

  // 输入备注
  remarkInput(e){
    this.setData({
      remark: e.detail.value
    });
  },

  addOrder: function(e){
    var that = this;
    var token = wx.getStorageSync('token');
    var user = wx.getStorageSync('user');
    for(var i=0; i< that.data.myCat.length;i++){
      
      var date = {
        "userId": user.userId,
        "price": that.data.myCat[i].price*that.data.myCat[i].num,
        "num": that.data.myCat[i].num,
        "productId": that.data.myCat[i].productId,
        "productName": that.data.myCat[i].name,
        "remark": that.data.myCat[i].productId,
        "addressId": that.data.addressList[that.data.addressIndex].id,
        "username": user.userName,
        "pic": that.data.myCat[i].pic
      };
      wx.request({
        url: 'http://127.0.0.1:8080/system/order', // 保存订单接口
        method: 'post',
        header: {
          'content-type': 'application/json',  //这里注意POST请求content-type是小写，大写会报错
          'Authorization': token
        },
        data:date,
        success(res) {
          if (res.statusCode==200) {
          }
        }
      });
    }
    setTimeout(() => {
      wx.showToast({
        title: "下单成功",
        icon: 'none',
      })
    }, 1000)
    wx.setStorageSync('myCat', '')
    wx.reLaunch({
      url: "/pages/shopping/index",
    })
  }

})